import { useEffect, useRef, useCallback } from "react";
import * as echarts from "echarts";
import "echarts-wordcloud";

interface WordCloudProps {
  id: number;
  name: string;
  value: number;
}

export default function WordCloud({ data }: { data: WordCloudProps[] }) {
  const target = useRef<HTMLDivElement>(null);
  /**
   * 生成随机色值
   */
  const randomRGB = () => {
    const r = Math.floor(Math.random() * 255);
    const g = Math.floor(Math.random() * 255);
    const b = Math.floor(Math.random() * 255);
    return `rgb(${r}, ${g}, ${b})`;
  };
  const initEcharts = useCallback(() => {
    if (target.current) {
      const myChart = echarts.init(target.current);
      // 渲染图表
      const options = {
        series: [
          {
            // 类型
            type: "wordCloud", // 数据映射文本的大小范围
            sizeRange: [8, 46], // 文字旋转范围
            rotationRange: [0, 0], // 单词之间的间距
            gridSize: 0, // 渲染动画
            layoutAnimation: true, // 字体
            textStyle: {
              // 随机色值
              color: randomRGB,
            }, // 高亮字体
            emphasis: {
              textStyle: {
                fontWeight: "bold",
                color: "#000",
              },
            }, // 数据
            data: data,
          },
        ],
      };

      myChart.setOption(options);
    }
  }, [data]); // 添加 data 作为依赖

  useEffect(() => {
    initEcharts();

    const handleResize = () => {
      initEcharts();
    };

    window.addEventListener("resize", handleResize);
    const targetCurrent = target.current;
    return () => {
      window.removeEventListener("resize", handleResize);

      if (targetCurrent) {
        echarts.dispose(targetCurrent);
      }
    };
  }, [initEcharts]); // 监视 initEcharts 的变化

  return (
    <div className="h-1/3 box-border pb-4">
      <div className="text-2xl text-white">【关键词条】</div>
      <div ref={target} className="w-full h-full"></div>
    </div>
  );
}
